﻿using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using System;
using DG.Tweening;
using UnityEngine.UI;
using QxFramework.Utilities;

namespace QxFramework.Core
{

    public class CommonMessageInfo
    {
        public string Info;
        public CommonMessageInfo(string info)
        {
            Info = info;
        }
    }


    /// <summary>
    /// 界面管理，提供管理界面和界面组的功能，如显示隐藏界面、激活界面。
    /// </summary>
    public class UIManager : MonoSingleton<UIManager>
    {
        /// <summary>
        /// UI预设目录，位于Assets/Resource/Prefabs/UI/
        /// </summary>
        public readonly string FoldPath = "Prefabs/UI/";

        /// <summary>
        /// 子面板对象列表
        /// </summary>
        private readonly List<Transform> _panels = new List<Transform>();

        /// <summary>
        /// 打开的UI列表
        /// </summary>
        private readonly List<KeyValuePair<string, UIBase>> _openUI = new List<KeyValuePair<string, UIBase>>();

        private GameObject MoneyObj;

        private CommonMessageInfo CurCommonMessage;
        private GameObject CurCommonMessageGo;

        /// <summary>
        ///  打开一个UI。
        /// </summary>
        /// <param name="uiName">UI预设的名称。</param>
        /// <param name="layer">显示在哪一个层。</param>
        /// <param name="args">附带的参数。</param>
        /// <returns></returns>
        public UIBase Open(string uiName, int layer = 1, object args = null)
        {
            //实例化UI
            GameObject ui = ResourceManager.Instance.Instantiate(FoldPath + uiName, _panels[layer]);

            //添加到UI键值对列表
            _openUI.Add(new KeyValuePair<string, UIBase>(uiName, ui.GetComponent<UIBase>()));

            //启动参数
            ui.GetComponent<UIBase>().OnDisplay(args);
            ui.GetComponent<UIBase>().OnRegisterHandler();

            return ui.GetComponent<UIBase>();
        }

        //T:自己转换成对应的ui类
        public T GetUILogic<T>(string uiName) where T:UIBase
        {
            foreach(var ui in _openUI)
            {
                if(ui.Key.Equals(uiName))
                {
                    return (T)ui.Value;
                }
            }
            Debug.LogError(uiName+"没有找到");
            return null;
        }

        /// <summary>
        ///  关闭指定名称的UI，是从后往前查找。
        /// </summary>
        /// <param name="uiName">UI名称。</param>
        public void Close(string uiName)
        {
            for (int i = _openUI.Count - 1; i >= 0; i--)
            {
                if (_openUI[i].Key == uiName)
                {
                    CloseUI(_openUI[i].Value);
                    _openUI.RemoveAt(i);
                    break;
                }
            }
        }

        /// <summary>
        ///  关闭指定UI对象。
        /// </summary>
        /// <param name="ui">ui对象</param>
        public void Close(UIBase ui)
        {
            for (int i = _openUI.Count - 1; i >= 0; i--)
            {
                if (_openUI[i].Value == ui)
                {
                    CloseUI(_openUI[i].Value);
                    _openUI.RemoveAt(i);
                    break;
                }
            }
        }

        /// <summary>
        /// 进行关闭和销毁处理。
        /// </summary>
        /// <param name="ui">UI对象</param>
        private void CloseUI(UIBase ui)
        {
            ui.OnClose();
            Destroy(ui.gameObject);
        }



        private void Awake()
        {
            //收集所有子对象
            for (int i = 0; i < transform.childCount; i++)
            {
                _panels.Add(transform.GetChild(i));
                //销毁现有的UI预设
                for (int j = _panels[i].childCount - 1; j >= 0; j--)
                {
                    Destroy(_panels[i].GetChild(j).gameObject);
                }
            }
            MoneyObj = ResourceManager.Instance.Load<GameObject>("Prefabs/Effect/MoneyEffect");
            ObjectPoolExtensions.CreatePool(MoneyObj,30);
        }

        // callBack 看是一个触发一下，还是全部显示完再触发
        public void SpawnMoneyEffect(int num,Vector3 startPosition,Vector3 targetPosition, Action callBack = null)
        {
            float speed = 800;
            num = num / 10;

            for(int i = 0;i<num;i++)
            {
                float x = UnityEngine.Random.Range(-1.0f,1.0f);
                float y = UnityEngine.Random.Range(-1.0f,1.0f);
                Vector3 direct = (new Vector3(x,y,0)).normalized;
                float force = UnityEngine.Random.Range(300.0f,500.0f);

                var firstPos = startPosition + direct*force;
                float distance = Vector2.Distance(firstPos,targetPosition);

                var moneyEffect = ObjectPoolExtensions.Spawn(MoneyObj,_panels[transform.childCount - 1]);
                moneyEffect.transform.GetComponent<RectTransform>().localPosition = startPosition;
                var seq = DOTween.Sequence();
                seq.Append(moneyEffect.transform.DOLocalMove(firstPos,0.2f).SetEase(Ease.OutQuad));
                //看看效果吧，可能要做距离越远时间长一些
                seq.Insert(0.2f,moneyEffect.transform.DOLocalMove(targetPosition,distance/speed).SetEase(Ease.InOutQuad));
                seq.AppendCallback(()=>{
                    //这里要刷新UI
                    ObjectPoolExtensions.Recycle(moneyEffect);
                   
                });
            }
            StartCoroutine(MoneyEffectCallBack(callBack));
        }
        
        private IEnumerator MoneyEffectCallBack(Action callBack )
        {
            yield return new WaitForSeconds(1);
            callBack();
        }

        public void ShowCommonMessage(CommonMessageInfo message)
        {
            if (CurCommonMessage != null)
            {
                if (message.Info == CurCommonMessage.Info)
                {
                    return;
                }

                CurCommonMessageGo.transform.DOKill();
                Destroy(CurCommonMessageGo);
                CurCommonMessage = null;
            }

            

            CurCommonMessage = message;
            CurCommonMessageGo = ResourceManager.Instance.Instantiate("Prefabs/UI/CommonMessageUI", _panels[_panels.Count - 1]);
            //CurCommonMessageGo.transform.Find("Text").GetComponent<Text>().text = message.Info;
            string tmpStr = TableAgent.Instance.GetString("Localization", message.Info, "Info");
            if (tmpStr == "")
            {
                CurCommonMessageGo.transform.Find("Text").GetComponent<Text>().text = message.Info;
            }
            else
            {
                CurCommonMessageGo.transform.Find("Text").GetComponent<Text>().text = tmpStr;
            }
            CurCommonMessageGo.GetComponent<CanvasGroup>().alpha = 0;
            var seq = DOTween.Sequence();
            seq.Append(CurCommonMessageGo.GetComponent<CanvasGroup>().DOFade(1, 0.3f));
            seq.Insert(2f, CurCommonMessageGo.transform.DOLocalMoveY(50, 0.5f));
            seq.Insert(2f, CurCommonMessageGo.GetComponent<CanvasGroup>().DOFade(0, 0.5f));
            seq.AppendCallback(() => {
                Destroy(CurCommonMessageGo);
                CurCommonMessage = null;
            });
        }

    }
}